<?php

namespace helper\cloud;

use AlibabaCloud\Client\AlibabaCloud;

class Alibaba
{

    private $option;

    /**
     * 实例化
     * @param $options
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function __construct($options)
    {
        if (is_array($options)) {
            $this->option = $options;
        } else {
            $this->option     = config('cloud.'.$options.'.config.alibaba');
        }
        AlibabaCloud::accessKeyClient($this->option['accessId'], $this->option['accessSecret'])
                    ->regionId($this->option['regionId'])
                    ->asDefaultClient();
    }

    /**
     * 获取配置参数
     * @param string $name
     * @return array|mixed
     */
    public function getOption($name=''){
        if(empty($name)) return $this->option;
        return $this->option[$name];
    }

    /**
     * 获取对应产品接口
     * @param $product
     * @param $version
     * @return mixed
     */
    public function getInterface($product, $version)
    {
        if (strpos($product, 'AlibabaCloud') === false) { //不包含命名空间
            $product = "\\AlibabaCloud\\{$product}\\{$product}";
        }
        return $product::$version();
    }

    /**
     * 直接执行指定方法
     * @param $product
     * @param $version
     * @param $fun
     * @param array $options 对应参数数组
     * @return mixed
     */
    public function execFun($product, $version, $fun, $options = [])
    {
        if (!isset($options['query'])) $options['query'] = $options;
        $interface = $this->getInterface($product, $version);
        $result    = $interface->$fun($options)->request();
        return $result->toArray();
    }

}